<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>管理页面</title>
	<style>
		div{
			margin-bottom:20px;
		}
	</style>
</head>
<body>
	
	<h1>用户与角色管理</h1>
	<div>
		请选择用户：
		<select name="user" id="userSelect">
			<option value="">请选择用户</option>
		</select>
	</div>

	<div id="checkbox">请选择角色：</div>

	<div><input type="button" value="确定" id="btn"></div>


	<script src="jquery-3.2.1.min.js"></script>
	<script>
		(function loadHtml(){
			$.ajax({
				url: "http://127.0.0.1/PHPStudy/RBAC/admin-loadHtml.php",
				dataType: "json",
				success: function(res){
					let userHtml=roleHtml="";
					res.user.forEach(function(e,i,arr){
						userHtml+=`
						  <option value="${e.uid}">${e.name}</option>
						          `;
					});
					$("#userSelect").append(userHtml);
					res.role.forEach(function(e,i,arr){
						roleHtml+=`
							<input type="checkbox" name="role" value="${e.code}">${e.name}
						          `;
					});
					$("#checkbox").append(roleHtml);
				}
			})
		})();

		/*选择用户事件*/
		$("#userSelect").change(function(){
			let uid = $(this).val();
			$.ajax({
				url: "http://127.0.0.1/PHPStudy/RBAC/admin-default.php",
				data: {uid: uid},
				type: "POST",
				dataType: "json",
				success: function(res){
					let checkbox = $("input:checkbox");
					$("input:checkbox").prop("checked",false);
					for(let i=0;i<checkbox.length;i++){
						let val = checkbox.eq(i).val();
						for(let j=0;j<res.length;j++){
							if(res[j].roleid == val){
								checkbox.eq(i).prop("checked",true);
							}
						}
					}
				}
			})
		});

		/*确定事件*/
		$("#btn").click(function(){
			let uid = $("#userSelect").val(); //获取用户名
			let vals = [];
      $('input:checkbox:checked').each(function (index, item) {
        vals.push($(this).val());
      });
      
      $.ajax({
      	url: "http://127.0.0.1/PHPStudy/RBAC/admin-save.php",
      	data: {uid: uid, roles: vals},
      	type: "POST",
      	dataType: "text",
      	success:function(res){
      		if(res.trim()=="OK"){
        		alert("保存成功！");
    　　		}
      	}
      })

		});



	</script>
</body>
</html>